<?php
header('Content-type:text/html; charset=UTF-8');

// locale version number
$newest_vernum = '';
if (preg_match('/^([\w\. ])+$/i', urldecode($_GET['vn'])) ) {
	$agent = '';
	$guest_vernum = $_GET['vn'];
	if (!empty($_SERVER['SCRIPT_FILENAME'])) {
		$path_parts = pathinfo($_SERVER['SCRIPT_FILENAME']);
		$path = $path_parts['dirname'];
	} else {
		$path = 'D:\wwwroot\upgrade\wwwroot';
	}
	
	require_once('pclzip.lib.php');
	// agent or not
	if ($_GET['tag'] == 'agent') {
		$agent = 'agent/';
		$path .= '/agent';
	}
} else {
	die('Request Failed!');
}

// offical version number
$orig_files = array();
$arr_files = is_array(glob($agent.'sitestar*.zip')) ? glob($agent.'sitestar*.zip') : array();
if (!sizeof($arr_files)) {
	if (file_exists($path)) {
		if ($dh = opendir($path)) {
			while (($file = readdir($dh)) !== false) {
				if (preg_match("/^sitestar\_v[0-9a-z\.\_]{1,}\.zip$/i", $file)) {
					$arr_files[] = $file;
				}
			}
			closedir($dh);
		}
	}
}
// newest offical version
$orig_files = $arr_files;
rsort($arr_files);
$newest_vernum = basename($arr_files[0], '.zip');
if ($newest_vernum <= $guest_vernum) { // don't upgrade
	$newest_vernum = $guest_vernum;
} else {
	// general upgrade folder-name
	$nstr = $nstr1 = $gstr = $gstr1 = '';
	$nstr1 = preg_replace('/[^\d]/', '', $newest_vernum);
	$nstr = strlen($nstr1) > 2 ? substr($nstr1, -4) : $nstr1;
	$gstr1 = preg_replace('/[^\d]/', '', $guest_vernum);
	$gstr = strlen($gstr1) > 2 ? substr($gstr1, -4) : $gstr1;
	$archive = "upgrade{$nstr}_{$gstr}";
	// general upgrade.zip
	if (!file_exists("{$path}/{$archive}.zip")) {
		sort($orig_files);
		foreach($orig_files as $mergefile) {
			$curent_vernum = basename($mergefile, '.zip');
			if ($guest_vernum < $curent_vernum) {
				// unzip specified files
				$zipmerge = new PclZip("{$mergefile}");
				$v_list = $zipmerge->extract(PCLZIP_OPT_PATH, $agent.$archive, 
				  						PCLZIP_CB_PRE_EXTRACT, "myPreExtractCallBack",
										PCLZIP_CB_POST_EXTRACT, 'myPostExtractCallBack');
				if ($v_list == 0) die('Error : '.$zipmerge->errorInfo(true));
			}
		}
		// zip upgrade
		$zip = new PclZip($agent."{$archive}.zip");
		$z_list = $zip->create($agent.$archive, PCLZIP_OPT_REMOVE_PATH, $agent.$archive);
		if ($z_list == 0) {
			die('Error : '.$zip->errorInfo(true));
		} else { // delete temp file
			if (!myRmdir($agent.$archive)) die('Error: Delete directory failed!');
		}
	}
}
echo $newest_vernum;

function myPreExtractCallBack($p_event, &$p_header) {
	global $curent_vernum;
	$info = pathinfo($p_header['filename']);
	$tmpdir = str_replace("agent/", '', $info['dirname']);
	if (($info['extension'] == 'sql') && !preg_match('/[\\/]+/', $tmpdir)) {
		$p_header['filename'] = $info['dirname']."/{$curent_vernum}_".$info['basename'];
		return 1;
	} else {
		return 1;
	}
}

function myPostExtractCallBack($p_event, &$p_header) {
	$info = pathinfo($p_header['filename']);
	$tmpdir = str_replace("agent/", '', $info['dirname']);
	if (($info['extension'] == 'sql') && 
	    !preg_match('/[\\/]+/', $tmpdir) && 
	    file_exists($p_header['filename'])) {
		$sql = file_get_contents($p_header['filename']);
		if ($handle = fopen($info['dirname'].'/basic.sql', 'ab')) {
			fwrite($handle, $sql."\r\n");
		}
		fclose($handle);
		unlink($p_header['filename']);
	}
	return 1;
}

function myRmdir($root_dir) {
    $files = scandir($root_dir);
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') continue;
        $f_path = $root_dir.'/'.$file;
        if (is_dir($f_path)) {
            if (!myRmdir($f_path)) return false;
        } else {
            if (!unlink($f_path)) return false;
        }
    }
    if (!rmdir($root_dir)) return false;
    
    return true;
}
?>